﻿#define _CRT_SECURE_NO_WARNINGS 1
#include"List.h"

LTNode* BuyLTNode(LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	//开辟空间失败
	if (newnode == NULL)
	{
		perror("BuyLTNode");
		exit(1);
	}
	newnode->val = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;

}
//创建一个哨兵位
LTNode* LTInit()
{
	LTNode* head = BuyLTNode(-1);
	head->next = head;
	head->prev = head;
	return head;
}
//链表的删除
void LTDestroy(LTNode* phead)
{
	assert(phead);
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		LTNode* next = cur->next;
		free(cur);
		cur = next;
	}

	free(phead);
}
void LTPrint(LTNode* phead)
{
	assert(phead);

	printf("head<=>");
	//打印从哨兵位的下一位开始
	LTNode* cur = phead->next;
	while (cur!=phead)
	{
		printf("%d<=>",cur->val);
		cur = cur->next;
	}
	printf("\n");
}
//判断链表是否为空
bool LTEmpty(LTNode* phead)
{	
	assert(phead);
	return phead->next ==phead;
}
//尾插
void LTPushBack(LTNode* phead, LTDataType x)
{
	/*assert(phead);
	LTNode* newnode = BuyLTNode(x);
	LTNode* tail = phead->prev;
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;*/
	//复用LTInsert
	LTInsert(phead, x);
}
//尾删
void LTPopBack(LTNode* phead)
{
	assert(phead);

	//链表为空
	if (LTEmpty(phead))
	{
		return;
	}
	/*LTNode* del = phead->prev;
	LTNode* tail = del->prev;
	tail->next = phead;
	phead->prev = tail;
	free(del);
	del = NULL;*/
	LTErase(phead->prev);
}
//头插
void LTPushFront(LTNode* phead, LTDataType x)
{
	/*assert(phead);
	LTNode* newnode = BuyLTNode(x);
	LTNode* start = phead->next;
	newnode->next = start;
	start->prev = newnode;
	newnode->prev = phead;
	phead->next = newnode;*/
	//复用LTInsert
	LTInsert(phead->next, x);
}
//头删
void LTPopFront(LTNode* phead)
{
	assert(phead);
	//链表为空
	if (LTEmpty(phead))
	{
		return;
	}
	/*LTNode* del = phead->next;
	LTNode* start = del->next;
	phead->next = start;
	start->prev = phead;
	free(del);
	del = NULL;*/
	LTErase(phead->next);
}

// 查找
LTNode* LֵTFind(LTNode* phead, LTDataType x)
{
	LTNode* cur = phead->next;
	while (cur!= phead)
	{
		if (cur->val == x)
		{
			return cur;
		}
		cur=cur->next;
	}
	return NULL;
}
//在pos位置之前插入
void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);
	LTNode* newnode = BuyLTNode(x);
	LTNode* prev= pos->prev;
	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
}
//删除pos位置
void LTErase(LTNode* pos)
{
	assert(pos);
	LTNode* prev = pos->prev;
	LTNode* next = pos->next;
	prev->next = next;
	next->prev = prev;
	free(pos);
}